<template>
  <div class="window-manager">
    <el-card class="app-card">
      <template #header>
        <div class="card-header">
          <span>Chrome窗口列表</span>
          <el-button type="primary" @click="importWindows">
            <el-icon><i-ep-upload /></el-icon>
            导入窗口
          </el-button>
        </div>
      </template>
      
      <div class="toolbar mb-20">
        <el-button-group>
          <el-button type="success" :disabled="!selectedWindows.length">
            <el-icon><i-ep-check /></el-icon>
            全选
          </el-button>
          <el-button type="info" :disabled="!selectedWindows.length">
            <el-icon><i-ep-close /></el-icon>
            取消选择
          </el-button>
          <el-button type="danger" :disabled="!selectedWindows.length" @click="closeSelectedWindows">
            <el-icon><i-ep-delete /></el-icon>
            关闭选中
          </el-button>
        </el-button-group>
        <el-button-group class="ml-4">
          <el-button type="primary" :disabled="!selectedWindows.length" @click="launchSelectedWindows">
            <el-icon><i-ep-caret-right /></el-icon>
            启动选中
          </el-button>
        </el-button-group>
      </div>
      
      <el-table
        v-loading="loading"
        :data="windows"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="number" label="窗口编号" width="100" />
        <el-table-column prop="title" label="窗口标题" min-width="300" />
        <el-table-column prop="pid" label="进程ID" width="100">
          <template #default="scope">
            {{ scope.row.pid || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="dataDir" label="用户数据目录" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button 
              v-if="scope.row.isRunning === true"
              type="danger" 
              size="small" 
              @click="closeWindow(scope.row.id)"
            >
              <el-icon><i-ep-close /></el-icon>
              关闭{{scope.row.id}}
            </el-button>
            <el-button 
              v-else
              type="primary" 
              size="small" 
              @click="launchWindow(scope.row.id)"
            >
              <el-icon><i-ep-caret-right /></el-icon>
              启动
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div v-if="!loading && windows.length === 0" class="empty-state">
        <el-empty description="暂无Chrome窗口" />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Upload, Check, Close, Delete, CaretRight } from '@element-plus/icons-vue'

// 使用别名以避免命名冲突
const iEpUpload = Upload
const iEpCheck = Check
const iEpClose = Close
const iEpDelete = Delete
const iEpCaretRight = CaretRight

interface ChromeWindow {
  id: number
  number: number
  title: string
  pid: number
  dataDir: string
  isRunning: boolean
  profileNumber: number
}

const windows = ref<ChromeWindow[]>([])
const loading = ref(false)
const selectedWindows = ref<ChromeWindow[]>([])

// 导入窗口
const importWindows = async () => {
  loading.value = true
  try {
    console.log('开始导入窗口数据...')
    const startTime = Date.now()
    
    // 并行调用两个API以提高性能
    const [profiles, runningWindows] = await Promise.all([
      window.electronAPI.getChromeWindows(),
      window.electronAPI.getRunningChromeWindows()
    ])
    
    const endTime = Date.now()
    console.log(`导入窗口数据完成，耗时: ${endTime - startTime}ms`)
    console.log('导入配置文件数据:', profiles)
    console.log('导入运行中的窗口数据:', runningWindows)
    
    // 创建一个map，用于快速查找运行中的窗口
    const runningWindowsMap = new Map()
    runningWindows.forEach(window => {
      runningWindowsMap.set(window.dataDir, window)
    })
    
    // 合并配置文件数据和运行中的窗口信息
    const mergedWindows: ChromeWindow[] = []
    let windowNumber = 1
    
    // 先添加运行中的窗口
    runningWindows.forEach(window => {
      mergedWindows.push({
        ...window,
        number: windowNumber++
      })
    })
    
    // 再添加未运行的配置文件
    profiles.forEach(profile => {
      if (!runningWindowsMap.has(profile.dataDir)) {
        mergedWindows.push({
          ...profile,
          isRunning: false, // 确保未运行的配置文件标记为false
          number: windowNumber++
        })
      }
    })
    
    windows.value = mergedWindows
    
    if (mergedWindows.length === 0) {
      ElMessage.info('未找到任何Chrome窗口或配置文件')
    } else {
      ElMessage.success(`成功导入 ${mergedWindows.length} 个窗口`)
    }
  } catch (error) {
    console.error('导入窗口失败:', error)
    ElMessage.error('导入窗口失败')
  } finally {
    loading.value = false
  }
}

// 处理选择变化
const handleSelectionChange = (selection: ChromeWindow[]) => {
  selectedWindows.value = selection
}

// 统一的窗口操作函数
const handleWindowAction = async (windowId: number, action: 'start' | 'close', pid?: number) => {
  try {
    console.log(`${action === 'start' ? '启动' : '关闭'}窗口，ID: ${windowId}${pid ? `, PID: ${pid}` : ''}`)
    
    let result
    if (action === 'start') {
      // 启动Chrome配置文件
      result = await window.electronAPI.launchChromeProfile(windowId)
    } else {
      // 关闭运行中的Chrome窗口，传递pid参数
      result = await window.electronAPI.closeRunningChromeWindow(windowId, pid)
    }
    
    if (result.success) {
      ElMessage.success(action === 'start' ? '浏览器已启动' : '窗口已关闭')
      
      if (action === 'start') {
        // 启动后刷新列表，使用较短的延迟确保能捕获到进程启动状态
        setTimeout(importWindows, 800)
        setTimeout(importWindows, 1500)
      }
    } else {
      ElMessage.error(`${action === 'start' ? '启动' : '关闭'}失败: ${result.error || '未知错误'}`)
    }
  } catch (error) {
    console.error(`${action === 'start' ? '启动' : '关闭'}失败:`, error)
    ElMessage.error(`${action === 'start' ? '启动' : '关闭'}失败`)
  }
}

// 关闭单个窗口
const closeWindow = async (windowId: number) => {
  // 查找对应的窗口获取pid
  const window = windows.value.find(w => w.id === windowId)
  const pid = window?.pid
  await handleWindowAction(windowId, 'close', pid)
}

// 启动单个窗口
const launchWindow = async (windowId: number) => {
  await handleWindowAction(windowId, 'start')
}

// 关闭选中窗口
const closeSelectedWindows = async () => {
  if (selectedWindows.value.length === 0) {
    ElMessage.warning('请先选择要关闭的窗口')
    return
  }
  
  try {
    let successCount = 0
    
    for (const chromeWindow of selectedWindows.value) {
      // 只关闭运行中的窗口
      if (chromeWindow.isRunning === true) {
        const result = await window.electronAPI.closeRunningChromeWindow(chromeWindow.id, chromeWindow.pid)
        if (result.success) {
          successCount++
        }
      }
    }
    
    if (successCount > 0) {
      ElMessage.success(`成功关闭 ${successCount} 个窗口`)
      // 更新窗口列表
      await importWindows()
    } else {
      ElMessage.error('没有可关闭的窗口')
    }
  } catch (error) {
    console.error('关闭选中窗口失败:', error)
    ElMessage.error('关闭选中窗口失败')
  }
}

// 启动选中窗口
const launchSelectedWindows = async () => {
  if (selectedWindows.value.length === 0) {
    ElMessage.warning('请先选择要启动的窗口')
    return
  }
  
  try {
    let successCount = 0
    
    for (const chromeWindow of selectedWindows.value) {
      // 只尝试启动未运行的窗口
      if (chromeWindow.isRunning === false) {
        const result = await window.electronAPI.launchChromeProfile(chromeWindow.id)
        if (result.success) {
          successCount++
        }
      }
    }
    
    if (successCount === 0) {
      ElMessage.info('未找到可启动的窗口（所选窗口可能已经在运行）')
    } else {
      ElMessage.success(`成功启动 ${successCount} 个浏览器`)
      // 使用较短的延迟和多次刷新，确保能捕获到进程启动状态
      setTimeout(importWindows, 800)
      // 再延迟一次刷新，确保进程完全启动并获取到进程ID
      setTimeout(importWindows, 1500)
    }
  } catch (error) {
    console.error('启动选中窗口失败:', error)
    ElMessage.error('启动选中窗口失败')
  }
}


// 组件挂载时导入窗口
onMounted(() => {
  importWindows()
})
</script>

<style lang="scss" scoped>
.window-manager {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .toolbar {
    display: flex;
    justify-content: flex-start;
    
    .ml-4 {
      margin-left: 16px;
    }
  }
  
  .empty-state {
    margin-top: 40px;
  }
}
</style>